using System;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace CKS.EBE.WebControls
{
    public class Menu : System.Web.UI.WebControls.Menu
    {
        XslTransformation _xslRender;

        public XslTransformation Xsl
        {
            get 
            {
                if (_xslRender == null) _xslRender = new XslTransformation();
                return _xslRender; 
            }

            set { _xslRender = value; }
        }


        protected virtual XmlDocument BuildDocument()
        {
            try
            {
                StringWriter sw = new StringWriter();
                XmlTextWriter w = new XmlTextWriter(sw);

                Uri currentPath = new Uri(SPContext.Current.Web.Url.ToLower());
                string sCurrentPath = currentPath.AbsolutePath.ToLower();

                w.WriteStartElement("Items");
                WriteNavigationNodes(this.Items, w, sCurrentPath);

                w.Close();
                sw.Close();

                XmlDocument oDoc = new XmlDocument();
                oDoc.LoadXml(sw.ToString());

                return oDoc;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                return null;
            }
        }

        protected virtual void WriteNavigationNodes(MenuItemCollection menuItemCollection, XmlTextWriter w, string sCurrentPath)
        {
            foreach (MenuItem oItem in menuItemCollection)
            {
                w.WriteStartElement("Item");
                
                w.WriteAttributeString("Url", oItem.NavigateUrl);
                w.WriteAttributeString("Title", oItem.Text);
                w.WriteAttributeString("Value", oItem.Value);
                w.WriteAttributeString("ValuePath", oItem.ValuePath);
                w.WriteAttributeString("ToolTip", oItem.ToolTip);
                w.WriteAttributeString("Target", oItem.Target);
                w.WriteAttributeString("Selected", oItem.Selected.ToString());
                w.WriteAttributeString("ImageUrl", oItem.ImageUrl);
                w.WriteAttributeString("Depth", oItem.Depth.ToString());
                w.WriteAttributeString("Enabled", oItem.Enabled.ToString());
                w.WriteAttributeString("Selectable", oItem.Selectable.ToString());
                w.WriteAttributeString("Current", (sCurrentPath+"/").StartsWith(oItem.DataPath + "/", StringComparison.OrdinalIgnoreCase).ToString());

                WriteNavigationNodes(oItem.ChildItems, w, sCurrentPath);

                w.WriteEndElement();
            }
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            Xsl.Document = BuildDocument();

            Xsl.RenderControl(writer);
        }
    }
}
